type WatchOptions = {
  folderPath?: string
  filePath?: string
  onFilesChanged?: () => void
  onFileChanged?: (filePath: string) => void
}

class WatchManager {
  private filesUnsub?: () => void
  private fileUnsub?: () => void

  async stopAll() {
    await window.fsApi?.stopWatch()
    this.filesUnsub?.()
    this.fileUnsub?.()
    this.filesUnsub = undefined
    this.fileUnsub = undefined
  }

  async start({ folderPath, filePath, onFilesChanged, onFileChanged }: WatchOptions) {
    await this.stopAll() // 保证安全重启
    await window.fsApi?.watch({ folderPath, filePath })

    // 注册事件
    if (onFilesChanged) {
      this.filesUnsub = window.fsApi.onFilesChanged(() => {
        // 简单防抖
        clearTimeout((this as any)._filesDebounce)
        ;(this as any)._filesDebounce = setTimeout(onFilesChanged, 200)
      })
    }

    if (onFileChanged) {
      this.fileUnsub = window.fsApi.onFileChanged((f: string) => {
        clearTimeout((this as any)._fileDebounce)
        ;(this as any)._fileDebounce = setTimeout(() => onFileChanged(f), 200)
      })
    }
  }
}

// 全局单例
export const watchManager = new WatchManager()

// 页面关闭安全清理
if (typeof window !== 'undefined') {
  window.addEventListener('beforeunload', () => watchManager.stopAll())
}
